<!-- 个人资料 -->
<template>
  <view class="wh-full-vh bg-main pt-30rpx">
    <view class="form-section">
      <van-form ref="baseFormRef" :label-width="80">
        <van-field name="avatar" label="头像">
          <template #input>
            <van-uploader
              v-model="imageList"
              :max-count="10"
              :multiple="false"
              :preview-image="false"
              :max-size="ImageUpload.maxSize * 1024 * 1024"
              accept="image/*"
              upload-text="选择图片"
              :before-read="beforeImageRead"
              :after-read="afterImageRead"
            >
              <van-image round width="4rem" height="4rem" :src="imgSrc" />
            </van-uploader>
          </template>
        </van-field>
        <van-field
          v-model="userInfo.nickName"
          name="nickName"
          label="昵称"
          placeholder="请输入昵称"
        />
        <van-field name="gender" label="性别">
          <template #input>
            <van-radio-group v-model="userInfo.gender" direction="horizontal">
              <van-radio v-for="item in genderOptions" :key="item.value" :name="item.value + ''">
                {{ item.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-model="userInfo.birthday"
          is-link
          readonly
          name="birthday"
          label="生日"
          placeholder="点击选择时间"
          @click="showPicker = true"
        />
        <van-field
          v-model="userInfo.signature"
          rows="3"
          autosize
          label="签名"
          type="textarea"
          placeholder="请输入签名"
        />
      </van-form>
      <van-button type="primary" round block @click="handleSubmit"> 提交 </van-button>
    </view>
    <van-popup v-model:show="showPicker" position="bottom">
      <van-date-picker @confirm="onConfirm" @cancel="showPicker = false" />
    </van-popup>
  </view>
</template>
<script setup lang="ts">
  import { onLoad } from '@dcloudio/uni-app';
  import { ref } from 'vue';
  import { userInfoApi, userEditApi } from '@/api/sys/user';
  import { Toast } from '@/utils/uniapi/prompt';
  import { uploadFile } from '@/utils/fileUtils';
  import { router } from '@/utils/router';
  import config from '@/utils/config';
  import { userInfoApi as infoApi } from '@/api/login';
  import { useUserStore } from '@/store/modules/user';
  import { ImageUpload } from '@/utils/config/fileConfig';
  import { isEmpty } from '@/utils/is';

  const userStore = useUserStore();

  /** 表单选择器 */
  const baseFormRef = ref();
  /** 图片列表 */
  const imageList = ref([]);
  /** 头像地址 */
  const imgSrc = ref('');
  /** 显示日期选择器 */
  const showPicker = ref(false);
  /** 用户信息 */
  const userInfo = ref<User.UserInfo>({
    id: '',
    username: '',
    avatar: '',
    nickName: '',
    gender: '',
    birthday: '',
    signature: '',
    status: '',
  });
  /** 性别选项 */
  const genderOptions = [
    {
      text: '男',
      value: 0,
    },
    {
      text: '女',
      value: 1,
    },
  ];

  /**
   * @description: 日期选择器
   * @param {object} e
   * @return {*}
   */
  const onConfirm = ({ selectedValues }) => {
    userInfo.value.birthday = selectedValues.join('-');
    showPicker.value = false;
  };

  /**
   * @description: 图片上传前校验
   * @param {any} rawFile 图片
   * @return {*}
   */
  const beforeImageRead = (rawFile) => {
    // 判断附件类型
    if (isEmpty(rawFile.type) || !ImageUpload.type.includes(rawFile.type)) {
      Toast('上传图片的格式不符合要求');
      return false;
    } else if (rawFile.size / 1024 / 1024 > ImageUpload.maxSize) {
      // 判断附件大小
      Toast('上传图片大小不能超过' + ImageUpload.maxSize + 'MB');
      return false;
    }
    return true;
  };

  /**
   * @description: 上传图片
   * @param {*} rawFile
   * @return {*}
   */
  const afterImageRead = (rawFile: any) => {
    if (Array.isArray(rawFile)) {
      rawFile.forEach((file) => {
        handleUploadFile(file);
      });
    } else {
      handleUploadFile(rawFile);
    }
  };

  /**
   * 上传附件
   * @param file 附件
   */
  const handleUploadFile = (rawFile: any) => {
    uploadFile(rawFile.file, (data) => {
      imgSrc.value = data.url;
    });
  };

  /** 获取用户信息 */
  const getUserInfo = async (id: string) => {
    await userInfoApi(id).then(({ data }) => {
      userInfo.value = data;
      imgSrc.value = data.avatar ? data.avatar : '';
    });
  };

  /** 表单提交 */
  const handleSubmit = () => {
    let info = userInfo.value;
    const param: User.UserInfo = {
      id: info.id,
      avatar: imgSrc.value,
      nickName: info.nickName,
      birthday: info.birthday,
      gender: info.gender,
      signature: info.signature,
    };
    userEditApi(param).then(async () => {
      const res = await infoApi();
      userStore.setUserInfo(res.data);
      router.reLaunch(config.route.user);
    });
  };

  onLoad(async (option) => {
    if (option && option.id) {
      await getUserInfo(option.id);
    } else {
      Toast('用户信息获取失败');
    }
  });
</script>
<style lang="scss">
  .form-section {
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 20rpx;
  }
  .popup {
    padding: 20rpx;
  }
  .menu-item {
    display: flex;
    height: 70rpx;
    align-items: center;
  }
  .menu-text {
    margin-left: 14rpx;
  }

  .menu-icon-right {
    width: 40rpx;
    line-height: 100%;
    height: 40rpx;
    margin-left: auto;
    color: #999999;
  }
</style>
